import {
  Directive,
  HostBinding,
  HostListener,
  Host,
  ElementRef,
  Renderer2,
  Input,
  Output,
  EventEmitter,
} from '@angular/core';
import { DragDropService } from '../directives.services';
@Directive({
  selector: '[app-draggable][dragTag][dragData][draggedClass]',
})
export class DragDirective {
  private _isDraggble = false;
  /*给标签设置draggable属性
   *true-能拖拽
   *false-不能拖拽
   */
  @Input('app-draggable')
  set isDraggable(value: boolean) {
    this._isDraggble = value;
    this.rd.setAttribute(this.el.nativeElement, 'draggable', `${value}`);
  }
  get isDraggable() {
    return this._isDraggble;
  }

  //拖拽开始时添加的class
  @Input()
  draggedClass: string;

  //给拖拽的元素定义dragTag标识（目标元素也会设置一个标识，用于判断该元素是否能拖到目标元素）
  @Input()
  dragTag: any;

  //给DragDropservice传递的数据（即目标元素的数据）
  @Input()
  dragData: any;

  //判断开始/结束拖拽时，部分区域的元素是不能设置为拖拽目标的（给不能拖拽的区域设置背景色）
  @Output()
  dragStart = new EventEmitter<any>();
  @Output()
  dragEnd = new EventEmitter<any>();

  constructor(
    private el: ElementRef,
    private rd: Renderer2,
    private service: DragDropService
  ) {}

  @HostListener('dragstart', ['$event'])
  ondragstart(ev: Event) {
    //判断drag元素是不是指令应用的元素发起的
    if (this.el.nativeElement === ev.target) {
      this.rd.addClass(this.el.nativeElement, this.draggedClass); //往el上增加一个class
      //进入时候给service传递上数据
      this.service.setDragData({ tag: this.dragTag, data: this.dragData });
      ev['dataTransfer'].setData('tag', this.dragTag); //兼容firefox,用来设置拖放操作的drag data到指定的数据和类型
      this.dragStart.emit(this.dragTag);
    }
  }

  @HostListener('dragend', ['$event'])
  ondragend(ev: Event) {
    if (this.el.nativeElement === ev.target) {
      this.rd.removeClass(this.el.nativeElement, this.draggedClass);
      this.dragEnd.emit(this.dragTag);
    }
  }
}
